<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="用户编号" prop="userNo">
        <el-input v-model="queryParams.userNo" placeholder="请输入用户编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable style="width: 200px">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['user:user:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户编号" align="center" prop="userNo" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template #default="scope">
          <el-avatar :size="40" :src="scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="账户信息" align="center" width="200">
        <template #default="scope">
          <div v-if="scope.row.userAccount">
            <div>余额：￥{{ scope.row.userAccount.balance || '0.00' }}</div>
            <div>积分：{{ scope.row.userAccount.points || '0' }}</div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template #default="scope">
          <div class="status-wrapper">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="scope.row.statusLoading"
              @change="handleStatusChange(scope.row)"
            />
            <span class="status-text" :class="{ 'is-active': scope.row.status === 1 }">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button v-hasPermi="['user:user:query']" link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button v-hasPermi="['user:user:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['user:user:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改用户对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar" :is-show-tip="false" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="viewOpen" title="用户详情" width="500px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户编号">{{ viewForm.userNo }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ viewForm.username }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <el-avatar :size="40" :src="viewForm.avatar" />
        </el-descriptions-item>
        <el-descriptions-item label="手机号">{{ viewForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ viewForm.email }}</el-descriptions-item>
        <el-descriptions-item label="微信OpenID">{{ viewForm.openid }}</el-descriptions-item>
        <el-descriptions-item label="支付宝ID">{{ viewForm.alipayId }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewForm.status === 1 ? 'success' : 'danger'">
            {{ viewForm.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="账户信息">
          <div v-if="viewForm.userAccount">
            <div>余额：￥{{ viewForm.userAccount.balance || '0.00' }}</div>
            <div>积分：{{ viewForm.userAccount.points || '0' }}</div>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="User">
import { listUser, getUser, addUser, updateUser, delUser } from '@/api/user/user';
import { UserQuery, UserVo, UserForm } from '@/api/user/user/types';
import { getToken } from '@/utils/auth';
import { Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import ImageUpload from '@/components/ImageUpload/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userList = ref<UserVo[]>([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const viewOpen = ref(false);
const viewForm = ref<UserVo>({} as UserVo);

// 表单ref
const userRef = ref<FormInstance>();
const queryRef = ref<FormInstance>();

// 用户状态选项
const statusOptions = ref([
  { label: '正常', value: 1 },
  { label: '禁用', value: 0 }
]);

// 查询参数
const queryParams = ref<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  userNo: undefined,
  username: undefined,
  phone: undefined,
  status: undefined
});

// 表单参数
const form = ref<UserForm>({
  id: undefined,
  userNo: undefined,
  username: '',
  phone: '',
  email: '',
  avatar: '',
  status: 1,
  deleted: 0
});

// 表单校验
const rules = ref<FormRules>({
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
});

/** 查询用户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then((response) => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    userNo: undefined,
    username: '',
    phone: '',
    email: '',
    avatar: '',
    status: 1,
    deleted: 0
  };
  userRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: UserVo[]) {
  ids.value = selection.map((item) => item.id!);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加用户';
}

/** 修改按钮操作 */
function handleUpdate(row?: UserVo) {
  reset();
  const id = row?.id || ids.value[0];
  getUser(id).then((response) => {
    console.log(response);
    Object.assign(form.value, response.data);
    open.value = true;
    title.value = '修改用户';
  });
}

/** 提交按钮 */
function submitForm() {
  userRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        updateUser(form.value).then((response) => {
          proxy?.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row?: UserVo) {
  const userIds = row?.id ? [row.id] : ids.value;
  proxy?.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(() => {
    delUser(userIds).then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    });
  });
}

/** 查看按钮操作 */
function handleView(row: UserVo) {
  getUser(row.id!).then((response) => {
    viewForm.value = response.data;
    viewOpen.value = true;
  });
}

/** 修改用户状态 */
function handleStatusChange(row: UserVo) {
  const text = row.status === 1 ? '启用' : '停用';
  row.statusLoading = true;
  updateUser({
    id: row.id,
    status: row.status
  })
    .then(() => {
      proxy?.$modal.msgSuccess(text + '成功');
    })
    .catch(() => {
      row.status = row.status === 0 ? 1 : 0;
    })
    .finally(() => {
      row.statusLoading = false;
    });
}

getList();
</script>

<style lang="scss" scoped>
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
  --el-switch-off-color: #f56c6c;
}

.status-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.status-text {
  font-size: 13px;
  color: #909399;

  &.is-active {
    color: #67c23a;
  }
}
</style>
